package com.bjsxt.commu3;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    private String name;
    private String color;
    boolean flag = false;       // true表示有产品，false表示没有产品

    private Lock lock = new ReentrantLock();
    //将等待队列分开
    private Condition produceCondition = lock.newCondition();
    private Condition consumeCondition = lock.newCondition();

    public void produce(int i) {
        lock.lock();
        try {
            //判断仓库是否为空，仓库不为空则等待消费
            if (flag) {
                try {
                    produceCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (i % 2 == 0) {
                this.name = "馒头";
                try {
                    Thread.sleep(10);       //只释放CPU，不释放锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.color = "白色";
            } else {
                this.name = "面包";
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.color = "黄色";
            }

            System.out.println("生产者生产一件商品：" + name + "，" + color);

            //改变仓库状态
            this.flag = true;

            //唤醒消费者
            consumeCondition.signal();
        } finally {
            lock.unlock();
        }
    }

    public void consume() {
        lock.lock();
        try {
            //如果仓库为空，则等待生产者生产
            if (!flag) {
                try {
                    consumeCondition.await();       //释放锁，等待生产者生产（必须在lock.lock()和lock.unlock()之间才能使用）
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("消费者消费一件商品：" + name + "，" + color);

            //改变仓库状态
            this.flag = false;

            //唤醒生产者
            produceCondition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
